import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  Image,
  ScrollView,
  ActivityIndicator,
} from 'react-native';
import { launchImageLibrary } from 'react-native-image-picker';
import Icon from 'react-native-vector-icons/Ionicons';
import { useNavigation } from '@react-navigation/native';
import SafeTabBarWrapper from '../components/SafeTabBarWrapper';
import { ToastManager } from '../components/Toast';
import { commonAPI, userAPI } from '../api';
import { COLORS, SHADOWS } from '../styles/constants';

const categories = [
  { id: 'BUG反馈', label: '功能异常' },
  { id: '景区讲解', label: '景区讲解' },
  { id: '线路建议', label: '线路建议' },
  { id: '其他', label: '其他' },
];

export default function FeedbackScreen() {
  const navigation = useNavigation();

  const [selectedCategory, setSelectedCategory] = useState(categories[0].id);
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [contact, setContact] = useState('');
  const [images, setImages] = useState([]); // [{uri: '', url: ''}]
  const [uploading, setUploading] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  // 选择图片
  const handleSelectImage = async () => {
    if (images.length >= 3) {
      ToastManager.warning('最多上传3张图片');
      return;
    }

    const options = {
      mediaType: 'photo',
      quality: 0.8,
      maxWidth: 1200,
      maxHeight: 1200,
      selectionLimit: 3 - images.length,
    };

    launchImageLibrary(options, async response => {
      if (response.didCancel) {
        return;
      }
      if (response.errorCode) {
        ToastManager.error('选择图片失败');
        return;
      }
      if (response.assets && response.assets.length > 0) {
        try {
          setUploading(true);
          ToastManager.info('正在上传图片...');

          const uploadedImages = [];

          for (const asset of response.assets) {
            // 构造文件对象
            const file = {
              uri: asset.uri,
              type: asset.type || 'image/jpeg',
              name: asset.fileName || `feedback_${Date.now()}.jpg`,
            };

            // 上传到服务器（使用 userAPI 的上传方法，与头像上传一致）
            const uploadResponse = await userAPI.uploadFile(file, 'feedback');

            // 获取上传后的URL（尝试多种可能的路径）
            const imageUrl =
              uploadResponse?.data?.data?.url ||
              uploadResponse?.data?.url ||
              uploadResponse?.url ||
              uploadResponse?.data?.data?.imageUrl ||
              uploadResponse?.data?.imageUrl;

            if (imageUrl) {
              uploadedImages.push({
                uri: asset.uri,
                url: imageUrl,
              });
            }
          }

          if (uploadedImages.length > 0) {
            setImages([...images, ...uploadedImages]);
            ToastManager.success(`成功上传 ${uploadedImages.length} 张图片`);
          } else {
            ToastManager.error('图片上传失败，请检查网络或重试');
          }
        } catch (error) {
          ToastManager.error(error.message || '图片上传失败，请重试');
        } finally {
          setUploading(false);
        }
      }
    });
  };

  // 删除图片
  const handleRemoveImage = index => {
    const newImages = images.filter((_, i) => i !== index);
    setImages(newImages);
  };

  // 提交反馈
  const handleSubmit = async () => {
    // 验证标题
    if (!title.trim()) {
      ToastManager.warning('请填写反馈标题');
      return;
    }

    // 验证内容
    if (!content.trim()) {
      ToastManager.warning('请填写反馈内容');
      return;
    }

    if (content.trim().length < 10) {
      ToastManager.warning('反馈内容至少需要10个字符');
      return;
    }

    // 验证联系方式（如果填写了）
    if (contact.trim()) {
      // 手机号格式验证（中国大陆手机号）
      const phoneRegex = /^1[3-9]\d{9}$/;
      // 邮箱格式验证
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

      const contactValue = contact.trim();

      // 判断是手机号还是邮箱
      if (contactValue.includes('@')) {
        // 验证邮箱格式
        if (!emailRegex.test(contactValue)) {
          ToastManager.warning('请输入正确的邮箱格式');
          return;
        }
      } else if (/^\d+$/.test(contactValue)) {
        // 如果全是数字，验证手机号格式
        if (!phoneRegex.test(contactValue)) {
          ToastManager.warning('请输入正确的手机号格式（11位数字）');
          return;
        }
      }
      // 其他格式（如微信号）不做验证
    }

    try {
      setSubmitting(true);
      ToastManager.info('正在提交反馈...');

      // 准备提交数据
      const feedbackData = {
        feedbackTitle: title.trim(),
        feedbackContent: content.trim(),
        feedbackType: selectedCategory,
        contactWay: contact.trim() || '',
        feedbackImgUrls:
          images.length > 0 ? images.map(img => img.url).join(',') : '',
        imgCount: images.length,
      };

      // 调用API提交反馈
      const response = await commonAPI.submitFeedback(feedbackData);

      if (response?.data?.code === 200) {
        ToastManager.success('提交成功，感谢您的反馈！');

        // 重置表单
        setTitle('');
        setContent('');
        setContact('');
        setImages([]);
        setSelectedCategory(categories[0].id);

        // 延迟返回到"我的"页面，让用户看到成功提示
        setTimeout(() => {
          navigation.navigate('Profile');
        }, 1500);
      } else {
        throw new Error(response?.data?.msg || '提交失败');
      }
    } catch (error) {
      ToastManager.error(error.message || '提交失败，请重试');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <SafeTabBarWrapper style={{ backgroundColor: COLORS.background.secondary }}>
      <ScrollView
        style={styles.container}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
      >
        {/* 反馈类型 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>反馈类型</Text>
          <View style={styles.categoryRow}>
            {categories.map(cat => {
              const active = cat.id === selectedCategory;
              return (
                <TouchableOpacity
                  key={cat.id}
                  style={[
                    styles.categoryTag,
                    active && styles.categoryTagActive,
                  ]}
                  onPress={() => setSelectedCategory(cat.id)}
                  activeOpacity={0.7}
                >
                  <Text
                    style={[
                      styles.categoryText,
                      active && styles.categoryTextActive,
                    ]}
                  >
                    {cat.label}
                  </Text>
                </TouchableOpacity>
              );
            })}
          </View>
        </View>

        {/* 反馈标题 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>反馈标题</Text>
          <View style={styles.card}>
            <TextInput
              style={styles.input}
              placeholder="简要描述您的问题..."
              placeholderTextColor="#bbb"
              value={title}
              onChangeText={setTitle}
              maxLength={50}
            />
            <Text style={styles.counter}>{title.length}/50</Text>
          </View>
        </View>

        {/* 反馈内容 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>反馈内容</Text>
          <View style={styles.card}>
            <TextInput
              style={styles.textArea}
              placeholder="请详细描述您遇到的问题或建议..."
              placeholderTextColor="#bbb"
              multiline
              value={content}
              onChangeText={setContent}
              maxLength={500}
            />
            <Text style={styles.counter}>{content.length}/500</Text>
          </View>
        </View>

        {/* 上传截图 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>上传截图（最多3张）</Text>
          <View style={styles.imagesContainer}>
            {images.map((img, index) => (
              <View key={index} style={styles.imageWrapper}>
                <Image source={{ uri: img.uri }} style={styles.imagePreview} />
                <TouchableOpacity
                  style={styles.removeBtn}
                  onPress={() => handleRemoveImage(index)}
                >
                  <Icon name="close-circle" size={24} color="#ff6b35" />
                </TouchableOpacity>
              </View>
            ))}

            {images.length < 3 && (
              <TouchableOpacity
                style={styles.uploadBox}
                onPress={handleSelectImage}
                disabled={uploading}
                activeOpacity={0.7}
              >
                {uploading ? (
                  <ActivityIndicator size="small" color="#ff6b35" />
                ) : (
                  <>
                    <Icon name="camera-outline" size={32} color="#ff6b35" />
                    <Text style={styles.uploadBoxText}>上传图片</Text>
                  </>
                )}
              </TouchableOpacity>
            )}
          </View>
        </View>

        {/* 联系方式 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>联系方式（选填）</Text>
          <View style={styles.card}>
            <TextInput
              style={styles.input}
              placeholder="微信号 / 手机号 / 邮箱"
              placeholderTextColor="#bbb"
              value={contact}
              onChangeText={setContact}
            />
          </View>
        </View>

        {/* 提交按钮 */}
        <TouchableOpacity
          style={[
            styles.submitButton,
            (submitting || uploading) && styles.submitButtonDisabled,
          ]}
          activeOpacity={0.8}
          onPress={handleSubmit}
          disabled={submitting || uploading}
        >
          <Text style={styles.submitText}>
            {submitting ? '提交中...' : '提交反馈'}
          </Text>
        </TouchableOpacity>
      </ScrollView>
    </SafeTabBarWrapper>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 16,
    paddingTop: 20,
  },
  section: {
    marginBottom: 20,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: COLORS.text.primary,
    marginBottom: 12,
  },
  categoryRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 10,
  },
  categoryTag: {
    paddingHorizontal: 14,
    paddingVertical: 8,
    borderRadius: 18,
    backgroundColor: COLORS.background.secondary,
  },
  categoryTagActive: {
    backgroundColor: COLORS.primaryLight,
    borderWidth: 1,
    borderColor: COLORS.primary,
  },
  categoryText: {
    fontSize: 14,
    color: COLORS.text.tertiary,
  },
  categoryTextActive: {
    color: COLORS.primary,
    fontWeight: '600',
  },
  card: {
    borderRadius: 16,
    backgroundColor: COLORS.background.card,
    padding: 16,
    ...SHADOWS.sm,
  },
  input: {
    fontSize: 14,
    color: COLORS.text.primary,
    minHeight: 40,
  },
  textArea: {
    minHeight: 140,
    fontSize: 14,
    color: COLORS.text.primary,
    textAlignVertical: 'top',
  },
  counter: {
    textAlign: 'right',
    marginTop: 8,
    fontSize: 12,
    color: COLORS.text.quaternary,
  },
  imagesContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 12,
  },
  imageWrapper: {
    position: 'relative',
  },
  imagePreview: {
    width: 100,
    height: 100,
    borderRadius: 12,
    backgroundColor: COLORS.background.secondary,
  },
  removeBtn: {
    position: 'absolute',
    top: -8,
    right: -8,
    backgroundColor: COLORS.background.card,
    borderRadius: 12,
    ...SHADOWS.sm,
  },
  uploadBox: {
    width: 100,
    height: 100,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: COLORS.primary,
    borderStyle: 'dashed',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: COLORS.primaryLight,
  },
  uploadBoxText: {
    marginTop: 4,
    fontSize: 12,
    color: COLORS.primary,
  },
  submitButton: {
    marginTop: 24,
    marginBottom: 32,
    borderRadius: 26,
    backgroundColor: COLORS.primary,
    paddingVertical: 14,
    alignItems: 'center',
    ...SHADOWS.md,
  },
  submitButtonDisabled: {
    backgroundColor: COLORS.border.dark,
    shadowOpacity: 0.1,
  },
  submitText: {
    fontSize: 16,
    color: COLORS.white,
    fontWeight: '600',
  },
});
